import requests
from lxml import etree
from time import sleep
import re
import random

class Csdn(object):
    def __init__(self,user_name):
        base_url = "http://blog.csdn.net/" + user_name + '/article/list/'
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'
        }
        self.url_list = [base_url+str(i+1) for i in range(10)]

    def get_data(self, url):
        response = requests.get(url=url, headers=self.headers)
        return response.content.decode()

    def parse_data(self, response):
        html = etree.HTML(response)
        node_list = html.xpath('//*[@id="article_list"]/div')
        if len(node_list) > 0:
            read_num = html.xpath('//*[@id="blog_rank"]/li[1]/span/text()')
            detail_url_list = []
            for node in node_list:
                detail_url = "http://blog.csdn.net" + node.xpath('./div[1]/h1/span/a/@href')[0]
                detail_url_list.append(detail_url)
            return detail_url_list, read_num
        else:
            detail_url_list = [0]
            read_num = 0
            return detail_url_list, read_num

    def get_detail_data(self, detail_url):
        response = requests.get(url=detail_url,headers=self.headers)
        return response.content.decode()

    def parse_datail_data(self, detail_response, read_num):
        title = re.search(r"<title>(.*)</title>", detail_response)
        print("当前浏览量为：{}．．．．正在刷CSDN博客访问量，当前文章：★★★".format(read_num), title.group(1), "★★★")

    def run(self):
        for url in self.url_list:
            response = self.get_data(url)
            # self.parse_data(response)
            detail_url_list, read_num = self.parse_data(response)
            if detail_url_list[0] != 0:
                for detail_url in detail_url_list:
                    # if detail_url != 0:
                        detail_response = self.get_detail_data(detail_url)
                        self.parse_datail_data(detail_response, read_num)
            else:
                break

if __name__ == '__main__':
    # page_total = input("请输入您的CSDN博客文章的总页数：")
    user_name = input("请输入您博客的用户：")
    csdn = Csdn(user_name)

    while True:
        n = random.randint(1,5)
        sleep(n)
        csdn.run()




